package com.superjson.showpro.dao.impl;

import com.superjson.showpro.base.GenericDaoImpl;
import com.superjson.showpro.dao.UserDao;
import com.superjson.showpro.entity.User;
import com.superjson.showpro.shared.util.CryptUtil;
import org.hamcrest.core.IsNull;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import static com.beantools.util.StringUtil.isNotBlank;

@Repository
public class UserDaoImpl extends GenericDaoImpl<User> implements UserDao {

    public UserDaoImpl() {
        super(User.class);
    }

    @Override
    public User existUser(String phoneOrAccName, String companyName) {
        String sql = "SELECT su.* FROM sp_user su WHERE su.is_deleted = 0" +
                " AND (su.phone = '" + phoneOrAccName + "' " +
                (isNotBlank(phoneOrAccName) ? "OR su.account_name='" + phoneOrAccName + "'" : "") +
                (isNotBlank(companyName) ? " OR su.company_name ='" + companyName + "'" : "") + ")";
        Query query = getSession().createSQLQuery(sql).addEntity(User.class);
        return (User) query.uniqueResult();
    }

    @Override
    public User getByAccNameOrPhone(String phoneOrAccName, String password) {
        String sql = "SELECT * FROM sp_user WHERE is_deleted = 0 AND (account_name = '" + phoneOrAccName + "'" +
                " or phone = '" + phoneOrAccName + "')" +
                " AND `password` = '" + CryptUtil.encrypt(password) + "'";
        Query query = getSession().createSQLQuery(sql).addEntity(User.class);
        return (User) query.uniqueResult();
    }
}